//默认配置
var mainConfig={};

$(document).ready(function(){
    mainConfig.checkboxColumn={
        className: "text-center",
        orderable: false,
        data: null,
        render: function (data, type, row, meta) {
            console.log(data);
            var html = '<label><input type="checkbox" value="' + data.id+ '" class="data-item ace"/><span class="lbl"></span></label>';
            return html;
        }
    };
    mainConfig.win={
        height:$(window).height() + "px",
        width:$(window).width() + "px"
    };

    // console.log('main config:', mainConfig);

    $.ajaxSetup({
        error:function(jqXHR, textStatus, errorMsg){
            top.loaded();
        }

    });
        //config layer
    layer.config({
        tipsMore:true
    });
    //config validator
    if($.validator){
        //验证框架默认提示
        $.validator.setDefaults({
            errorClass:'label-error small'
        });
    }

    //config datatable
    var table_lang = {
        "sProcessing": "处理中...",
        "sLengthMenu": "每页 _MENU_ 项",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
        "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "上页",
            "sNext": "下页",
            "sLast": "末页",
            "sJump": "跳转"
        }
    };
    $.extend( $.fn.dataTable.defaults, {
        language:table_lang,  //提示信息
        "autoWidth": false,  //禁用自动调整列宽
        stripeClasses: ["odd", "even"],  //为奇偶行加上样式，兼容不支持CSS伪类的场合
        processing: true,  //隐藏加载提示,自行处理
        serverSide: true,  //启用服务器端分页
        searching: false,  //禁用原生搜索
        orderMulti: false,  //启用多列排序
        order: [],  //取消默认排序查询,否则复选框一列会出现小箭头
        renderer: "bootstrap",  //渲染样式：Bootstrap和jquery-ui
        paging: true,
        pagingType: "simple_numbers",  //分页样式：simple,simple_numbers,full,full_numbers
        scrollX:false,
        iDisplayLength: 30,//每页显示条数
        ordering: true,//默认表头排序
        columnDefs:[{ "targets": "_all" }],
        "lengthMenu": [30, 50, 100, 200, 300, 400]

    } );

    tableAjax = function(form,data, callback, settings){
        var pageData = {};
        pageData.pageSize = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
        pageData.pageNum = (data.start / data.length)+1;//当前页码
        if(typeof(data.order[0]) != "undefined"){
            if(data.columns[data.order[0].column].name){
                pageData.orderColumn = data.columns[data.order[0].column].name;
            }else{
                pageData.orderColumn = data.columns[data.order[0].column].data;
            }
            pageData.orderDir = data.order[0].dir;
        }
        form.ajaxSubmit({
            dataType:'json',
            data:pageData,
            success:function(result){
                if(result && result.success){
                    //封装返回数据
                    var obj = {};
                    obj.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                    obj.recordsTotal = result.data.total;//返回数据全部记录
                    obj.recordsFiltered = result.data.total;//后台不实现过滤功能，每次查询均视作全部结果
                    obj.data = result.data.list;//返回的数据列表
                    callback(obj);
                }else{
                    layer.alert(result.msg ? result.msg : "查询出现错误，请更改参数后重试");
                    callback({draw:0, recordsTotal:0, recordsFiltered:0, data:[]});
                }
            }
        });
    }


    $('.check-all').on('click' , function(){
        var that = this;
        $('#'+$(this).data('tableid')).find('input:checkbox')
            .each(function(){
                this.checked = that.checked;
            });

    });

    $('select.selectpicker').selectpicker({liveSearch: true,style:'btn-light'});

    $('.form-tabindex input,.form-tabindex select').keydown(function (e) {
        var $input = $(this);
        var inputs = $('.form-tabindex input:visible');
        var maxindex = inputs.length;
        var tabindex = 1 + inputs.index(this);
        var key = e.keyCode;
        if(key == 13){
            if(maxindex > tabindex){
                inputs.eq(tabindex).focus();
            }else{
                $('.form-tabindex').submit();
            }
        }
    });
    $('.form-tabindex #saveBtn').click(function(){
        $(this).closest('form').submit();
    });

    //新增、修改、详情
    $('#main-container').on("click",".link_add,.link_edit,.link_info",function(){
        var _this = $(this);
        var url = _this.data('url');

        var title = _this.data('title');
        var height = _this.data('height') ? _this.data('height') : mainConfig.win.height;
        var width = _this.data('width') ? _this.data('width') : mainConfig.win.width;

        if(!title){
            if(_this.hasClass('link_add')){
                title = "新增";
            }else if(_this.hasClass('link_edit')){
                title = '修改';
            }else if(_this.hasClass('link_info')){
                title  = '详情';
            }
        }



        if (url) {
            //如果是修改没有根id,则从对应的表格中找已选中的数据修改
            if (_this.hasClass('link_edit') || _this.hasClass('link_info')) {
                var ids = getCheckedValues($('.data-item:checked'), {max: 1});
                console.log(ids);
                if (!ids) {
                    return;
                }
                url += "/" + ids[0];
            }

            var beforeFun = _this.data('function');
            var validateSuccess = true;
            if(beforeFun) {
                beforeFun = window[beforeFun];
                validateSuccess = beforeFun(ids);
            }
            if(!validateSuccess){
                return;
            }

            var layerIndex = layer.open({
                title: title,
                type: 2,
                content: url,
                area: [width, height]
            });
        }//end if
        return false;
    });// end add edit

    //删除
    $('#main-container').on("click",'.link_del',function(){
        var _this = $(this);
        var url = _this.data('url');
        var title = _this.attr('title');
        var formId = _this.data('form');
        if(url){
            //如果是修改没有根id,则从对应的表格中找已选中的数据修改
            if(/.*\/delete$/.test(url)){
                var arr = $('.data-item:checked');
                var ids = getCheckedValues(arr, {});
                if(!ids){
                    return;
                }
                url += "/" + ids.join(',');
            }

            var beforeFun = _this.data('function');
            var validateSuccess = true;
            if(beforeFun) {
                beforeFun = window[beforeFun];
                validateSuccess = beforeFun(ids);
            }
            if(!validateSuccess){
                return;
            }

            var msg = "确定要删除此记录吗?";
            if(_this.data('msg')){
                msg = _this.data('msg');
            }
            layer.confirm(msg, function(index) {
                layer.close(index);
                $.ajax({
                    url: url,
                    type: "DELETE",
                    dataType: "json",
                    success: function (data) {
                        if(data.success){
                            if(!formId){
                                formId = 'searchForm';
                            }
                            $('#'+formId).submit();
                        }else{
                            layer.alert(data.msg);
                        }
                    }
                });
            });
        }//end if url
        return false;
    });// end 删除

    $('.link_close').click(function(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    });
    $('.link_print').click(function(){
        $(".dataTables_wrapper").print({
            globalStyles: true,
            mediaPrint: false,
            stylesheet: null,
            noPrintSelector: ".dataTables_paginate,.dataTables_length",
            iframe: true,
            append: null,
            prepend: null,
            manuallyCopyFormValues: true,
            deferred: $.Deferred()
        });
    });

    $('.link_export').click(function(){
        var url = $(this).attr('url') ? $(this).attr('url') : 'export';
        var formId = $(this).parent().data('form') ? $(this).parent().data('form') : 'searchForm';
        var form = $('#' + formId);
        window.open(url + '?' + form.serialize(), '_blank');
        return false;
    });

    // begin 分页查询
    $(".pagination a.btn_page").on("click", function() {
        var nextPage = $(this).data("pagenum");
        var form = $(this).closest('form');
        if(form.length > 0){
            if ($.isNumeric(nextPage)) {
                form.find("input[name=pageNum]").val(nextPage);
                form.find('input[name=export]').remove();
                form.submit();
            }
        }
    });

    $(".pagination .btn_page_jump").on('click', function(e) {
        var pageNum = $(this).closest('ul').find('.txt_page_num').val();
        if(/^\d*$/.test(pageNum) && pageNum > 0){
            var form = $(this).closest('form');
            form.find("input[name=pageNum]").val(pageNum);
            form.find('input[name=export]').remove();
            form.submit();
        }
    });

    $(".pagination .txt_page_num").on("change",function(e){
        var pageNum = $(this).closest('ul').find('.txt_page_num').val();
        var form = $(this).closest('form');
        var totalpage = form.find("input[name=totalpage]").val();
        if(!/^\d*$/.test(pageNum) || pageNum <= 0 || pageNum > totalpage){
            $(this).closest('ul').find('.txt_page_num').val('');
        }
    });

    $(".pagination .pageSize").on("change",function(e){
        var pageSize = $(this).val();
        var form = $(this).closest('form');
        form.find("input[name=pageNum]").val(1);
        form.find("input[name=pageSize]").val(pageSize);
        form.find('input[name=export]').remove();
        form.submit();

    }); // end 分页

    //搜索按钮
    $('#searchBtn,.btn_form_search').on('click',function(e){
        var form = $(this).closest('form');
        form.find("input[name=pageNum]").val(1);
        form.find('input[name=export]').remove();
        form.submit();
        return false;
    });
    //导出按钮
    $('#exportBtn').on('click',function(){
        var form = $(this).closest('form');
        var input_export = form.find('input[name=export]');
        if(input_export && input_export.length > 0){
            input_export.val(1);
        }else{
            form.append('<input type="hidden" name="export" value="1" />');
        }
        form.submit();
    });

    $(document).keyup(function(event) {
        if (event.keyCode == 13) {
            $("#searchBtn").trigger("click");
        }
    });

});

/**
 * 格式化tabelData数据，如果在某个范围内就高亮显示
 * @param data
 * @param type
 * @param row
 * @param meta
 * @returns {*}
 */
function formatRate (data, type, row, meta) {
    var min = $('#rateMin').val();
    var max = $('#rateMax').val();
    if(min || max){
        var html = '';
        if(min && max){
            if((data - min >=0) && (max-data >= 0)){
                return '<span class="bg-error">' + data + '</span>';
            }
        }else if(min && (data - min >=0)){
            return '<span class="bg-error">' + data + '</span>';
        }else if(max && (max - data >=0)){
            return '<span class="bg-error">' + data + '</span>';
        }
    }
    return data;
}
/**
 * 获取已选中的checkbox 的值
 * @param checkedArr 已选中的checkbox 数组
 * @param option 限制参数{min,max}
 * @returns 数组或undefined
 */
function getCheckedValues(checkedArr, option){
    var vals =[];
    if(!option){
        option = {};
    }
    if(option.required == undefined){
        option.required = true;
    }

    if(option.required){
        if(checkedArr.length == 0){
            layer.alert("未选择记录");
            return;
        }
    }

    if(option.max == 1 && checkedArr.length > 1){
        layer.alert('一次只能操作一条记录');
        return ;
    }

    checkedArr.each(function(n, item){
        console.log(item);
        vals.push(item.value);
    });
    return vals;
}

function closeIframe(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function openIframe(option){
    var layerIndex = layer.open({
        title:option.title,
        type: 2,
        content: option.url,
        area: [option.width ? option.width : mainConfig.width, option.height ? option.height : mainConfig.height]
    });
}

